package com.smartcampusbackend.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartcampusbackend.model.User;
import com.smartcampusbackend.mapper.UserMapper;
import com.smartcampusbackend.service.UserService;
import com.smartcampusbackend.util.ExcelUtil;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public void register(User user) {
        // 校验用户名唯一
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username", user.getUsername());
        if (baseMapper.selectOne(query) != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 校验邮箱唯一
        if (user.getEmail() != null && !user.getEmail().trim().isEmpty()) {
            QueryWrapper<User> emailQuery = new QueryWrapper<>();
            emailQuery.eq("email", user.getEmail().trim());
            if (baseMapper.selectOne(emailQuery) != null) {
                throw new RuntimeException("邮箱已被注册");
            }
        }
        
        // 校验学号唯一（学生角色）
        if ("STUDENT".equals(user.getRole()) && user.getStudentId() != null && !user.getStudentId().trim().isEmpty()) {
            QueryWrapper<User> studentIdQuery = new QueryWrapper<>();
            studentIdQuery.eq("student_id", user.getStudentId().trim());
            if (baseMapper.selectOne(studentIdQuery) != null) {
                throw new RuntimeException("学号已存在");
            }
        }
        
        // 校验工号唯一（教师角色）
        if ("TEACHER".equals(user.getRole()) && user.getTeacherId() != null && !user.getTeacherId().trim().isEmpty()) {
            QueryWrapper<User> teacherIdQuery = new QueryWrapper<>();
            teacherIdQuery.eq("teacher_id", user.getTeacherId().trim());
            if (baseMapper.selectOne(teacherIdQuery) != null) {
                throw new RuntimeException("工号已存在");
            }
        }
        
        // 密码加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.setPassword(encoder.encode(user.getPassword()));
        
        // 设置默认角色
        if (user.getRole() == null) {
            user.setRole("STUDENT");
        }
        
        baseMapper.insert(user);
    }

    @Override
    public User login(String username, String password) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username", username);
        User user = baseMapper.selectOne(query);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(password, user.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        return user;
    }

    @Override
    public User getByUsernameAndRole(String username, String role) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username", username);
        query.eq("role", role);
        return baseMapper.selectOne(query);
    }

    @Override
    public boolean updateUser(User user) {
        return baseMapper.updateById(user) > 0;
    }

    public User getByUsername(String username) {
        // 你用的 MyBatis-Plus
        return lambdaQuery().eq(User::getUsername, username).one();
    }

    @Override
    public IPage<User> pageUsers(int page, int size, String username, String role, Integer status) {
        Page<User> p = new Page<>(page, size);
        QueryWrapper<User> qw = new QueryWrapper<>();
        if (username != null && !username.isEmpty()) qw.like("username", username);
        if (role != null && !role.isEmpty()) qw.eq("role", role);
        if (status != null) qw.eq("status", status);
        return baseMapper.selectPage(p, qw);
    }

    @Override
    public Map<String, Object> importUsersFromExcel(MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        int success = 0, fail = 0;
        StringBuilder failMsg = new StringBuilder();
        try {
            List<User> users = ExcelUtil.readUsersFromExcel(file);
            for (User user : users) {
                try {
                    this.save(user);
                    success++;
                } catch (Exception e) {
                    fail++;
                    failMsg.append(user.getUsername()).append(": ").append(e.getMessage()).append("; ");
                }
            }
        } catch (Exception e) {
            result.put("code", 400);
            result.put("msg", "文件解析失败: " + e.getMessage());
            return result;
        }
        result.put("code", 200);
        result.put("msg", "导入完成");
        result.put("success", success);
        result.put("fail", fail);
        result.put("failMsg", failMsg.toString());
        return result;
    }
}
